// src/store/index.ts
import { createPinia } from "pinia";
import { createPersistedState } from "pinia-plugin-persistedstate";
import { SessionCrypto } from "../utils/crypto";

export const pinia = createPinia();

pinia.use(
	createPersistedState({
		storage: {
			// 解密读取
			getItem: async (key: string) => {
				try {
					const data = sessionStorage.getItem(key);
					if (!data) return null;

					// 添加数据完整性校验
					if (data.length < 30) throw new Error("Invalid data length");
					return JSON.parse(await SessionCrypto.decrypt(data));
				} catch (error) {
					console.error("Decryption failed, clearing storage:", error);
					sessionStorage.removeItem(key);
					return null;
				}
			},

			// 加密存储
			setItem: async (key: string, value: string) => {
				const encrypted = await SessionCrypto.encrypt(value);
				sessionStorage.setItem(key, encrypted);
			},

			// 移除数据
			removeItem: (key: string) => sessionStorage.removeItem(key),
		},
	})
);

export default pinia;
